package 力扣日常刷题.木23一月.第04天304;

/**
 * @author 帅小伙
 * @date 2022/3/4
 * @description
 */
public class Demo35岛屿的数量 {

    public int numIslands(char[][] grid) {
        if(grid == null || grid.length == 0)return 0;
        int n = grid.length,m = grid[0].length;
        int ans = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if(grid[i][j] == '1') {
                    ans++;
                    dfs(grid,i,j);
                }
            }
        }
        return ans;
    }

    public void dfs(char[][]grid,int i,int j) {
        int n = grid.length,m = grid[0].length;
        if(i <0 || i >= n || j < 0 || j >= m || grid[i][j] == '0') return;

        grid[i][j] = '0';
        int[] dx = {1,-1,0,0};
        int[] dy = {0,0,1,-1};
        for (int k = 0; k < 4; k++) {
            dfs(grid,i+dx[k],j+dy[k]);
        }
    }

}
